package cn.mengfly.fxtest.app.urltest;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Optional;

/**
 * @author Mengfly
 */
public class UrlTestModel {

    private final Notifications notifications = new Notifications();

    private Optional<UrlTestObject> urlTestObject = Optional.empty();

    public Optional<UrlTestObject> getUrlTestObject() {
        return urlTestObject;
    }

    public Optional<UrlTestObject> testUrl(String url) {
        long startTimeMillis = System.currentTimeMillis();
        try {
            HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
            try (InputStream is = urlConnection.getInputStream()) {
                while (is.read() != -1) {
                }
            }
            long endTimeMillis = System.currentTimeMillis();
            UrlTestObject uto = new UrlTestObject(urlConnection.getResponseCode(),(int)(endTimeMillis - startTimeMillis));
            urlTestObject = Optional.of(uto);
            urlConnection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            UrlTestObject uto = new UrlTestObject(e.getMessage());
            urlTestObject = Optional.of(uto);
        }

        notifications.publish(Notifications.EVENT_MODEL_UPDATE);
        return urlTestObject;
    }
}
